package initialition

import (
	"encoding/json"
	"exam-app/user-srv/global"
	"exam-app/user-srv/internal/model/dao"
	"fmt"
	"github.com/go-redis/redis"
	"github.com/nacos-group/nacos-sdk-go/clients"
	"github.com/nacos-group/nacos-sdk-go/common/constant"
	"github.com/nacos-group/nacos-sdk-go/vo"
	"github.com/spf13/viper"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"log"
	"os"
)

func init() {
	InitConfig()
	InitNacos()
	InitDB()
	InitRdb()
}
func InitConfig() {

	viper.SetConfigFile("./config/dev.yaml")
	err := viper.ReadInConfig()
	if err != nil {
		panic(err)
	}
	viper.Unmarshal(&global.NacosConfig)
	fmt.Println("nacos配置参数", global.NacosConfig)
}
func InitNacos() {

	os.MkdirAll("./tmp/nacos/log", 0777)
	os.MkdirAll("./tmp/nacos/cache", 0777)
	//create clientConfig
	clientConfig := constant.ClientConfig{
		NamespaceId:         global.NacosConfig.Nacos.NameSpace,
		TimeoutMs:           5000,
		NotLoadCacheAtStart: true,
		LogDir:              "./tmp/nacos/log",
		CacheDir:            "./tmp/nacos/cache",
		LogLevel:            "debug",
		Username:            global.NacosConfig.Nacos.UserName,
		Password:            global.NacosConfig.Nacos.Password,
	}
	// At least one ServerConfig
	serverConfigs := []constant.ServerConfig{
		{
			IpAddr:      global.NacosConfig.Nacos.Addr,
			ContextPath: "/nacos",
			Port:        global.NacosConfig.Nacos.Port,
			Scheme:      "http",
		},
	}
	// Another way of create config client for dynamic configuration (recommend)
	configClient, err := clients.NewConfigClient(
		vo.NacosClientParam{
			ClientConfig:  &clientConfig,
			ServerConfigs: serverConfigs,
		},
	)
	if err != nil {
		panic(err)
	}
	content, err := configClient.GetConfig(vo.ConfigParam{
		DataId: global.NacosConfig.Nacos.DataId,
		Group:  global.NacosConfig.Nacos.Group})
	//fmt.Println(content)
	err = json.Unmarshal([]byte(content), &global.GlobalConfig)
	if err != nil {
		log.Fatalf("nacos配置解析失败%v", err)
	}
	fmt.Println("nacos解析配置参数", global.GlobalConfig)
}
func InitDB() {
	var err error
	config := global.GlobalConfig.Mysql
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8&parseTime=True", config.User, config.Password, config.Host, config.Port, config.Database)
	global.DB, err = gorm.Open(mysql.Open(dsn))
	if err != nil {
		panic(err)
	}
	log.Println("mysql连接成功")
	global.DB.AutoMigrate(&dao.Users{})
}
func InitRdb() {
	global.Rdb = redis.NewClient(&redis.Options{
		Addr:     global.GlobalConfig.Redis.Host,
		Password: global.GlobalConfig.Redis.Password,
	})
	err := global.Rdb.Ping().Err()
	if err != nil {
		panic(err)
	}
	log.Println("redis连接成功")
}
